package com.github_dididipapa.mallsearch.service.impl;

import com.alibaba.fastjson2.JSON;
import com.github_dididipapa.common.to.es.SkuEsModel;
import com.github_dididipapa.mallsearch.constant.ElasticSearchOptionsConstant;
import com.github_dididipapa.mallsearch.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.security.AuthenticateRequest;
import org.elasticsearch.client.security.AuthenticateResponse;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: To be defined
 * @author: dididi_papa
 * @email: mitis1624087624@gmail.com
 * @date: 2025/07/04  10:27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
    // ES客户端
    private final RestHighLevelClient client;
    @Override
    public boolean saveSpu(List<SkuEsModel> esModelList) throws IOException {
        if (esModelList.isEmpty()) return false;

        BulkRequest bulkRequest = new BulkRequest();
        esModelList.forEach(esModel -> {
            IndexRequest request = new IndexRequest("product");
            request.id(esModel.getSkuId().toString());
            String info = JSON.toJSONString(esModel);
            request.source(info, XContentType.JSON);
            bulkRequest.add(request);
        });

        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchOptionsConstant.COMMON_OPTIONS.getOption());
        boolean flag = !bulk.hasFailures();// 出错时返回True, 没有出错时返回False; 害惨我了， 找了一个小时才找到原因
        List<String> collect = Arrays.stream(bulk.getItems())
                .map(BulkItemResponse::getId)
                .collect(Collectors.toList());
        if(!flag) log.error("ES同步数据失败{}", collect);

        return flag;
    }
}
